﻿using System;
using System.Threading.Tasks;
using Windows.System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Navigation;
using com.IronOne.BoardPACWinApp.Common;
using com.IronOne.BoardPACWinApp.Helpers;
using com.IronOne.BoardPACWinAppBO.Auth;
using com.IronOne.BoardPACWinAppService.Auth;
using com.IronOne.BoardPACWinAppUtil.Enums;
using com.IronOne.BoardPACWinAppUtil.Util;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace com.IronOne.BoardPACWinApp.View.UserControl.SettingPanels
{
    /// <summary>
    ///     An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class SettingPersonalInfo
    {
        private readonly IAuthService _authService;
        private readonly IDialogService _dialogService;

        public SettingPersonalInfo()
        {
            InitializeComponent();
            _dialogService = new DialogService();
            _authService = new AuthService();
        }

        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            try
            {
                base.OnNavigatedTo(e);

                var um = await _authService.GetUserFromId();
                TxtName.Text = um.UserFullName;
                TxtDisplayName.Text = um.IPadDisplayName;
                TxtEmail.Text = um.Email;

                ImgProfilePic.Source = await BasePage.UpdateProfilePic(um.UserId);


                //Change password section
                var polText =
                    await
                        _authService.GetSettingValueBySettingName(DatabaseType.UserDb,
                            ApplicationConstants.UserDbSettingNames.PasswordPolicyText);
                if (polText == null)
                {
                    PolicyTxt.Visibility = Visibility.Collapsed;
                    return;
                }

                var pol = polText.ToString().Replace("<br/>", " ");
                pol = pol.Replace("; ", "\n");
                PolicyTxt.Text = pol;
            }
            catch (Exception)
            {
            }
            finally
            {
                PgbPage.Visibility = Visibility.Collapsed;
            }
        }

        /*private void Cancel_ChangePassword_Click(object sender, RoutedEventArgs e)
        {

        }*/

        private void txt_OldPassword_KeyUp(object sender, KeyRoutedEventArgs e)
        {
            if (e.Key == VirtualKey.Enter)
            {
                if (!String.IsNullOrWhiteSpace(TxtOldPassword.Password))
                {
                    TxtNewPassword.Focus(FocusState.Keyboard);
                }
                if (!String.IsNullOrWhiteSpace(TxtNewPassword.Password))
                {
                    TxtConfirmNewPassword.Focus(FocusState.Keyboard);
                }
            }
        }

        private void txt_NewPassword_KeyUp(object sender, KeyRoutedEventArgs e)
        {
            if (e.Key == VirtualKey.Enter)
            {
                if (!String.IsNullOrWhiteSpace(TxtNewPassword.Password))
                {
                    TxtConfirmNewPassword.Focus(FocusState.Keyboard);
                }
            }
        }

        private async void txt_ConfirmNewPassword_KeyUp(object sender, KeyRoutedEventArgs e)
        {
            if (e.Key == VirtualKey.Enter)
            {
                await ChangePasswordCommon();
            }
        }

        private async Task ChangePasswordCommon()
        {
            try
            {
                BtnChangePassword.IsEnabled = false;

                var rslt = await ChangePasswordProcess();
                if (rslt)
                {
                    await _dialogService.ShowMessage("Password changed successfully");
                    TxtOldPassword.Password = "";
                    TxtNewPassword.Password = "";
                    TxtConfirmNewPassword.Password = "";
                }
            }
            finally
            {
                BtnChangePassword.IsEnabled = true;
            }
        }

        private async Task<bool> ChangePasswordProcess()
        {
            try
            {
                var logOnModel = new LogOnModel
                {
                    OldPassword = TxtOldPassword.Password,
                    NewPassword = TxtNewPassword.Password,
                    ConfirmNewPassword = TxtConfirmNewPassword.Password
                };

                if ((String.IsNullOrWhiteSpace(logOnModel.OldPassword)) &&
                    (String.IsNullOrWhiteSpace(logOnModel.NewPassword)) &&
                    (String.IsNullOrWhiteSpace(logOnModel.ConfirmNewPassword)))
                {
                    await _dialogService.ShowMessage("Password fields cannot be empty");
                    TxtOldPassword.Focus(FocusState.Keyboard);
                    return false;
                }

                if (String.IsNullOrWhiteSpace(logOnModel.OldPassword))
                {
                    await _dialogService.ShowMessage("Old password cannot be empty");
                    TxtOldPassword.Focus(FocusState.Keyboard);
                    return false;
                }

                if (String.IsNullOrWhiteSpace(logOnModel.NewPassword))
                {
                    await _dialogService.ShowMessage("New password cannot be empty");
                    TxtNewPassword.Focus(FocusState.Keyboard);
                    return false;
                }

                if (String.IsNullOrWhiteSpace(logOnModel.ConfirmNewPassword))
                {
                    await _dialogService.ShowMessage("Confirm new password cannot be empty");
                    TxtConfirmNewPassword.Focus(FocusState.Keyboard);
                    return false;
                }

                if (!logOnModel.NewPassword.Equals(logOnModel.ConfirmNewPassword))
                {
                    await _dialogService.ShowMessage("New password and confirm new password does not match");
                    return false;
                }

                PgbChangePassword.Visibility = Visibility.Visible;
                var rdm = await _authService.ChangePassword(logOnModel);

                PgbChangePassword.Visibility = Visibility.Collapsed;
                if (rdm.IsError)
                {
                    await _dialogService.ShowMessage(rdm.ErrorMessage);
                    return false;
                }

                //If "IsError" false means "ErrorMessage" contains success message
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        private async void btn_ChangePassword_Click(object sender, RoutedEventArgs e)
        {
            await ChangePasswordCommon();
        }
    }
}